package cn.itcast.crawler;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@SuppressWarnings("all")
public class DemoFirst {
    public static void main(String[] args) {
        // 创建浏览器客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 发起Get请求，设置url地址
        String url = "http://www.itcast.cn";
        HttpGet httpGet = new HttpGet(url);

        // 由于需要释放资源，所以在try...catch外部定义响应对象
        CloseableHttpResponse response = null;
        try {
            // 接受响应
            response = httpClient.execute(httpGet);

            // 判断响应状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                // 如果状态吗为200，表明此时响应成功，之后解析响应内容即可
                // 获取内容 设置utf8的响应编码，否则输出的数据会有乱码
                String content = EntityUtils.toString(response.getEntity(),"utf8");
                // 输出获取内从和长度
                System.out.println("获取的内容长度："+content.length());
                System.out.println("实际获取的内容：");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
